<template>
  <div class="employees-container">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <div class="left">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增员工
        </el-button>
        <el-upload
          class="excel-upload"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          accept=".xlsx,.xls"
          @change="handleExcelChange"
        >
          <el-button type="success">
            <el-icon><Upload /></el-icon>导入Excel
          </el-button>
        </el-upload>
      </div>
      <div class="right">
        <el-input
          v-model="searchQuery"
          placeholder="搜索工号/姓名/所属/部门"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 员工列表 -->
    <el-table
      v-loading="loading"
      :data="employees"
      style="width: 100%"
      border
    >
      <el-table-column prop="employee_id" label="工号" width="120" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="affiliation" label="所属" width="120" />
      <el-table-column prop="dept1" label="一级部门" width="150" />
      <el-table-column prop="dept2" label="二级部门" width="150" />
      <el-table-column prop="dept3" label="三级部门" width="150" />
      <el-table-column prop="position" label="职位" width="150" />
      <el-table-column prop="hire_date" label="入职日期" width="120" />
      <el-table-column prop="leave_date" label="离职日期" width="120" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增员工' : '编辑员工'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="工号" prop="employee_id">
          <el-input v-model="form.employee_id" placeholder="请输入工号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="所属" prop="affiliation">
          <el-input v-model="form.affiliation" placeholder="请输入所属" />
        </el-form-item>
        <el-form-item label="一级部门" prop="dept1">
          <el-input v-model="form.dept1" placeholder="请输入一级部门" />
        </el-form-item>
        <el-form-item label="二级部门" prop="dept2">
          <el-input v-model="form.dept2" placeholder="请输入二级部门" />
        </el-form-item>
        <el-form-item label="三级部门" prop="dept3">
          <el-input v-model="form.dept3" placeholder="请输入三级部门" />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="form.position" placeholder="请输入职位" />
        </el-form-item>
        <el-form-item label="入职日期" prop="hire_date">
          <el-date-picker
            v-model="form.hire_date"
            type="date"
            placeholder="选择入职日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="离职日期" prop="leave_date">
          <el-date-picker
            v-model="form.leave_date"
            type="date"
            placeholder="选择离职日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Plus, Upload, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useEmployeeStore } from '@/stores/employee'
import { useExcelImport } from '@/hooks/useExcelImport'
import type { FormInstance, FormRules } from 'element-plus'
import { storeToRefs } from 'pinia'
import type { Employee } from '@/types/employee'

// 状态管理
const employeeStore = useEmployeeStore()
const { employees, loading } = storeToRefs(employeeStore)

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const form = ref({
  employee_id: '',
  name: '',
  affiliation: '',
  dept1: '',
  dept2: '',
  dept3: '',
  position: '',
  hire_date: '',
  leave_date: ''
})

// 表单验证规则
const rules = {
  employee_id: [
    { required: true, message: '请输入工号', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  affiliation: [
    { required: true, message: '请输入所属', trigger: 'blur' }
  ],
  dept1: [
    { required: true, message: '请输入一级部门', trigger: 'blur' }
  ],
  dept2: [
    { required: true, message: '请输入二级部门', trigger: 'blur' }
  ],
  dept3: [
    { required: true, message: '请输入三级部门', trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请输入职位', trigger: 'blur' }
  ],
  hire_date: [
    { required: true, message: '请选择入职日期', trigger: 'change' }
  ]
}

// Excel导入
const { readExcelFile, validateImportData } = useExcelImport()

// 搜索相关
const searchQuery = ref('')
const originalEmployees = ref<Employee[]>([])

// 获取员工列表
const fetchEmployees = async () => {
  try {
    await employeeStore.fetchEmployees()
    originalEmployees.value = [...employeeStore.employees]
  } catch (error) {
    ElMessage.error('获取员工列表失败')
  }
}

// 搜索处理
const handleSearch = () => {
  if (!searchQuery.value) {
    employeeStore.employees = [...originalEmployees.value]
    return
  }

  const query = searchQuery.value.toLowerCase()
  employeeStore.employees = originalEmployees.value.filter((employee: Employee) => {
    return (
      employee.employee_id.toLowerCase().includes(query) ||
      employee.name.toLowerCase().includes(query) ||
      employee.affiliation.toLowerCase().includes(query) ||
      employee.dept1.toLowerCase().includes(query) ||
      employee.dept2.toLowerCase().includes(query) ||
      employee.dept3.toLowerCase().includes(query)
    )
  })
}

// 新增员工
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    employee_id: '',
    name: '',
    affiliation: '',
    dept1: '',
    dept2: '',
    dept3: '',
    position: '',
    hire_date: '',
    leave_date: ''
  }
  dialogVisible.value = true
}

// 编辑员工
const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 格式化数据
        const submitData = {
          ...form.value,
          employee_id: String(form.value.employee_id),
          hire_date: form.value.hire_date ? new Date(form.value.hire_date).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-') : '',
          leave_date: form.value.leave_date ? new Date(form.value.leave_date).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-') : undefined
        }

        if (dialogType.value === 'add') {
          await employeeStore.createEmployee(submitData)
        } else {
          await employeeStore.updateEmployee(
            submitData.employee_id,
            submitData
          )
        }
        dialogVisible.value = false
        ElMessage.success(
          dialogType.value === 'add' ? '新增成功' : '更新成功'
        )
        // 刷新数据
        await fetchEmployees()
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

// 处理Excel文件上传
const handleExcelChange = async (file: any) => {
  try {
    // 指定工作表名和字段映射
    const sheetName = '人员基本信息'
    const headerMap = {
      '工号': 'employee_id',
      '姓名': 'name',
      '所属': 'affiliation',
      '一级部门': 'dept1',
      '二级部门': 'dept2',
      '三级部门': 'dept3',
      '职位': 'position',
      '入职日期': 'hire_date',
      '离职日期': 'leave_date'
    }
    
    const data = await readExcelFile(file.raw, headerMap, sheetName)
    
    // 验证数据
    const requiredFields = [
      'employee_id',
      'name',
      'affiliation',
      'dept1',
      'dept2',
      'dept3',
      'position',
      'hire_date'
    ]
    if (!validateImportData(data, requiredFields)) {
      return
    }
    
    // 批量创建员工
    const formattedEmployees = data.map(item => ({
      employee_id: String(item.employee_id),
      name: item.name,
      affiliation: item.affiliation,
      dept1: item.dept1,
      dept2: item.dept2,
      dept3: item.dept3,
      position: item.position,
      hire_date: item.hire_date ? new Date(item.hire_date).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-') : '',
      leave_date: item.leave_date ? new Date(item.leave_date).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-') : undefined
    }))
    
    const result = await employeeStore.batchCreateEmployees(formattedEmployees)
    
    if (result) {
      ElMessage.success('导入成功')
      // 手动刷新列表
      await fetchEmployees()
    }
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败: ' + (error instanceof Error ? error.message : String(error)))
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchEmployees()
})
</script>

<style scoped>
.employees-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.operation-bar .left {
  display: flex;
  gap: 10px;
}

.operation-bar .right {
  display: flex;
  align-items: center;
}

.search-input {
  width: 300px;
}

.excel-upload {
  display: inline-block;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 添加表格容器样式 */
:deep(.el-table) {
  flex: 1;
  overflow: auto;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

:deep(.el-table__inner-wrapper) {
  height: 100%;
}

:deep(.el-table__body) {
  height: 100%;
}
</style> 